<script>
  import { ref, onMounted, computed } from 'vue'
  import api from '@/utils/api'
  import Toast from '@/components/Toast.vue'
  import { showToast } from '@/utils/toast'
  
  export default {
    components: {
      Toast
    },
    setup() {
      const notifications = ref([]) // 存储通知列表数据
      const current_page = ref(1) // 当前页码
      const page_size = ref(10) // 每页显示数量
      const totalNotifications = ref(0) // 通知总数

      // 计算总页数
      const totalPages = computed(() => {
        return Math.ceil(totalNotifications.value / page_size.value)
      })

      // 处理家庭邀请
      const handleInvite = async (notificationId, accept) => {
        try {
          const response = await api.post('/api/handle_invite', {
            notification_id: notificationId,
            accept: accept
          })
          if (response.data.code === 0) {
            showToast(accept ? '已接受邀请' : '已拒绝邀请', 'success')
            // 刷新通知列表
            await getNotifications()
          } else {
            showToast(response.data.message || '操作失败', 'error')
          }
        } catch (error) {
          showToast('操作失败', 'error')
        }
      }

      // 处理加入申请
      const handleJoin = async (notificationId, accept) => {
        try {
          const response = await api.post('/api/handle_Join', {
            notification_id: notificationId,
            accept: accept
          })
          if (response.data.code === 0) {
            showToast(accept ? '已接受申请' : '已拒绝申请', 'success')
            // 刷新通知列表
            await getNotifications()
          } else {
            showToast(response.data.message || '操作失败', 'error')
          }
        } catch (error) {
          showToast('操作失败', 'error')
        }
      }
  
      // 获取通知列表
      const getNotifications = async () => {
        try {
          const response = await api.get('/api/get_notifications', {
            params: {
              current_page: current_page.value,
              page_size: parseInt(page_size.value)
            }
          })
          if (response.data.code === 0) {
            notifications.value = response.data.data
            totalNotifications.value = response.data.total
          }
        } catch (error) {
          showToast('获取通知失败', 'error')
        }
      }
  
      // 处理页码变化
      const handlePageChange = (page) => {
        current_page.value = page
        getNotifications()
      }
  
      // 处理每页显示数量变化
      const handlePageSizeChange = (event) => {
        page_size.value = parseInt(event.target.value)
        current_page.value = 1
        getNotifications()
      }
  
      // 组件挂载时获取通知列表
      onMounted(getNotifications)
  
      // 格式化日期显示
      const formatDate = (dateString) => {
        const options = { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' }
        return new Intl.DateTimeFormat('zh-CN', options).format(new Date(dateString))
      }

      /**
       * 判断未处理的家庭邀请消息
       * @param {string} message - 通知消息内容（来自notification.message）
       * @param {number} is_warning - 通知状态（来自notification.is_warning）
       *                0: 未处理，1: 警告状态，2: 已完成, 3：需要操作
       * @returns {boolean} 是否符合邀请消息条件
       */
      const isInviteMessage = (message, is_warning) => {
        return message.includes('邀请你加入家庭') && is_warning === 3
      }

      /**
       * 判断未处理的加入申请消息 
       * @param {string} message - 通知消息内容（来自notification.message）
       * @param {number} is_warning - 通知状态（来自notification.is_warning）
       *                0: 未处理，1: 警告状态，2: 已完成, 3：需要操作
       * @returns {boolean} 是否符合加入申请条件
       */
      const isJoinMessage = (message, is_warning) => {
        return message.includes('申请加入家庭') && is_warning === 3
      }
  
      return {
        notifications,
        formatDate,
        handleInvite,
        handleJoin,
        isInviteMessage,
        isJoinMessage,
        current_page,
        page_size,
        totalNotifications,
        totalPages,
        handlePageChange,
        handlePageSizeChange
      }
    }
  }
</script>

<template>
  <div class="notification-container">
    <Toast />
    <h2>系统通知</h2>
    <ul>
      <li v-for="notification in notifications" 
          :key="notification.id" 
          class="notification-item"
          :class="{ 
            'warning': notification.is_warning === 1,
            'success': notification.is_warning === 2 
          }">
        <div class="notification-content">
          <svg class="notification-icon" viewBox="0 0 24 24" width="16" height="16">
            <path fill="currentColor" d="M12 22c1.1 0 2-.9 2-2h-4c0 1.1.9 2 2 2zm6-6v-5c0-3.07-1.63-5.64-4.5-6.32V4c0-.83-.67-1.5-1.5-1.5s-1.5.67-1.5 1.5v.68C7.64 5.36 6 7.92 6 11v5l-2 2v1h16v-1l-2-2zm-2 1H8v-6c0-2.48 1.51-4.5 4-4.5s4 2.02 4 4.5v6z"/>
          </svg>
          <span class="message">{{ notification.message }}</span>
          
          <!-- 邀请操作按钮 -->
          <div v-if="isInviteMessage(notification.message, notification.is_warning)" class="invite-actions">
            <button 
              class="accept-btn" 
              @click="handleInvite(notification.id, true)"
            >
              接受
            </button>
            <button 
              class="reject-btn" 
              @click="handleInvite(notification.id, false)"
            >
              拒绝
            </button>
          </div>

          <!-- 加入操作按钮 -->
          <div v-if="isJoinMessage(notification.message, notification.is_warning)" class="invite-actions">
            <button 
              class="accept-btn" 
              @click="handleJoin(notification.id, true)"
            >
              接受
            </button>
            <button 
              class="reject-btn" 
              @click="handleJoin(notification.id, false)"
            >
              拒绝
            </button>
          </div>


          <!-- 已处理状态显示 -->
          <div v-else-if="notification.message.includes('邀请你加入家庭') || notification.message.includes('申请加入家庭')" class="status-text">
            {{ notification.is_warning === 2 ? '已接受' : '已拒绝' }}
          </div>
        </div>
        <span class="notification-time">{{ formatDate(notification.created_at) }}</span>
      </li>
    </ul>

    <div class="pagination" v-if="notifications.length > 0">
      <span class="total-records">共 {{ totalNotifications }} 条</span>
      <select :value="page_size" @change="handlePageSizeChange" class="page-size-select">
        <option :value="10">10条/页</option>
        <option :value="20">20条/页</option>
        <option :value="50">50条/页</option>
        <option :value="100">100条/页</option>
      </select>
      <button 
        @click="handlePageChange(current_page - 1)" 
        :disabled="current_page === 1" 
        class="page-btn"
      >
        上一页
      </button>

      <div class="page-numbers">
        <button 
          v-for="page in totalPages" 
          :key="page" 
          @click="handlePageChange(page)" 
          :class="{'active': page === current_page}"
        >
          {{ page }}
        </button>
      </div>

      <button 
        @click="handlePageChange(current_page + 1)" 
        :disabled="current_page * page_size >= totalNotifications" 
        class="page-btn"
      >
        下一页
      </button>
    </div>
  </div>
</template>

<style scoped>
  .notification-container {
    padding: 20px;
    margin: 20px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  }
  
  h2 {
    margin-bottom: 20px;
    font-size: 24px;
    color: #333;
  }
  
  ul {
    list-style-type: none;
    padding: 0;
  }
  
  .notification-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    background: #f8f9fa;
    margin-bottom: 10px;
    padding: 15px 20px;
    border-radius: 8px;
    font-size: 16px;
    color: #333;
    transition: all 0.3s ease;
  }
  
  .notification-item:hover {
    background: #edf2ff;
  }
  
  .notification-item.warning {
    background: #fef0f0;
    color: #f56c6c;
    border: 1px solid #fbc4c4;
  }
  
  .notification-item.warning .notification-icon {
    color: #f56c6c;
  }
  
  .notification-item.warning .notification-time {
    color: #f56c6c;
  }
  
  .notification-item.warning:hover {
    background: #fde2e2;
  }
  
  .notification-item.success {
    background: #f0f9eb;
    color: #67c23a;
    border: 1px solid #c2e7b0;
  }
  
  .notification-item.success .notification-icon {
    color: #67c23a;
  }
  
  .notification-item.success .notification-time {
    color: #67c23a;
  }
  
  .notification-item.success:hover {
    background: #e1f3d8;
  }
  
  .notification-content {
    display: flex;
    align-items: center;
    gap: 12px;
    flex: 1;
  }
  
  .notification-icon {
    color: #409eff;
    flex-shrink: 0;
  }
  
  .message {
    flex-grow: 1;
  }
  
  .notification-time {
    font-size: 14px;
    color: #909399;
    margin-left: 20px;
  }
  
  .invite-actions {
    display: flex;
    gap: 10px;
    margin-left: 20px;
  }
  
  .accept-btn,
  .reject-btn {
    padding: 4px 12px;
    border-radius: 4px;
    border: none;
    cursor: pointer;
    font-size: 14px;
    transition: all 0.3s;
  }
  
  .accept-btn {
    background: #67c23a;
    color: white;
  }
  
  .accept-btn:hover {
    background: #85ce61;
  }
  
  .reject-btn {
    background: #f56c6c;
    color: white;
  }
  
  .reject-btn:hover {
    background: #f78989;
  }

  .status-text {
    font-size: 14px;
    padding: 4px 12px;
    border-radius: 4px;
    margin-left: 20px;
    color: #909399;
    background: #f4f4f5;
  }

  .pagination {
    display: flex;
    align-items: center;
    margin-top: 20px;
    flex-wrap: wrap;
    gap: 8px;
  }

  .total-records {
    color: #606266;
    font-size: 14px;
  }

  .page-size-select {
    height: 30px;
    font-size: 14px;
    padding: 0 10px;
    margin: 0 8px;
    border-radius: 4px;
    border: 1px solid #dcdfe6;
    background: white;
  }

  .page-btn {
    margin: 0 5px;
    padding: 5px 10px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    background: white;
    cursor: pointer;
  }

  .page-btn:disabled {
    cursor: not-allowed;
    opacity: 0.6;
  }

  .page-numbers {
    display: flex;
    margin: 0 8px;
    flex-wrap: wrap;
    gap: 4px;
  }

  .page-numbers button {
    font-size: 14px;
    margin: 0 4px;
    padding: 5px 10px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    background: white;
    cursor: pointer;
  }

  .page-numbers button.active {
    background: #409eff;
    color: white;
    border-color: #409eff;
  }
</style>
